<?php

class ArticleAction extends Action{
	/*获取内容列表*/
	public function checkList($countWhere,$dataWhere,$order){
		import("@.ORG.Page");
		$count = M('News')->where($countWhere)->count('id');
		$p     = new Page ($count,C('listnews'));
		$list = M()->Table(array(C('DB_PREFIX').'news'=>'news',C('DB_PREFIX').'user'=>'user'))->where($dataWhere)->order($order)->limit($p->firstRow.','.$p->listRows)->select();
		$p->setConfig('theme','%totalRow% %header% %first% %prePage% %linkPage% %nextPage% %end%');
		$page = $p->show();
		foreach($list as $key=>$value){
			$list[$key]['title'] = $value['title'];
			$list[$key]['face'] = C('YICMS_PUBLIC').'/face/f_'.$value['face'];
			$list[$key]['mpic'] = C('URL').'/Public/news/s/m_'.$value['pic'];
			$list[$key]['spic'] = C('URL').'/Public/news/s/s_'.$value['pic'];
			if(!empty($value['tag'])) $list[$key]['tag'] = explode(' ',$value['tag']);
			if(C('opencws')){
				$list[$key]['content'] = preg_replace('/yi_show\((.*?),event\)/',"yi_show(\\1,event,".$value['id'].")",$value['content']);
			}else{
				$list[$key]['content'] = strip_tags($value['content']);
			}
		}
		
		if(!empty($list)) $this->assign('count',$count);
		else $this->assign('count',0);
		$this->assign('list',$list);
		$this->assign('page',$page);
	}
	
	/*获取公共参数*/
	public function about(){
		$this->assign('HOME_PUBLIC',C('HOME_PUBLIC'));
		$this->assign('YICMS_PUBLIC',C('YICMS_PUBLIC'));
		$this->assign('about',M('About')->find());		
		$nav = M('nav')->where('state = 0 AND id != 1')->field('name,sname')->limit('3')->order('taxis asc')->select();
		$this->assign('nav',$nav);		
	}
	
	/*糗事内页*/
	public function article(){
		$this->about();
		/*接收分享链接的参数*/
		$id = explode('#',$_GET['_URL_'][2]);
		$id = (int)$id[0];
		
		$res = M('News')->where("id = $id")->find();
		if(!$res){
			$this->error('没有找到这个帖子');
		}
		M('News')->where("id = $id")->setInc('click',1);
		$news = M()->Table(array(C('DB_PREFIX').'news'=>'news',C('DB_PREFIX').'user'=>'user'))->where("news.id = $id AND news.state = 1 AND news.uid = user.uid")->find();
		/*	判断是否开启了tag标签匹配	*/
		if(C('opencws')){
			$news['content'] = preg_replace('/yi_show\((.*?),event\)/',"yi_show(\\1,event,".$news['id'].")",$news['content']);
		}else{
			$news['content'] = strip_tags($news['content']);
		}
		$news['mpic'] = C('URL').'/Public/news/m_'.$news['pic'];
		$news['face'] = C('URL').'/Public/face/f_'.$news['face'];
		if(!empty($news['tag'])){
			$tags = $news['tag'];
			$news['tag'] = explode(' ',$news['tag']);
		}
		$this->assign('news',$news);
		$reply = M()->Table(array(C('DB_PREFIX').'reply'=>'reply',C('DB_PREFIX').'user'=>'user'))->where("reply.pid = $id AND reply.state = 1 AND reply.arid = user.uid")->order('reply.artime ASC')->select();
		$this->assign('reply',$reply);
		$config = M('Config')->find();
		if($news['title']){
			$config['title'] = $news['title'].'-'.$config['stitle'];
		}else{
			$config['title'] = '糗事#'.$news['id'].'-'.$config['stitle'];
		}	
		if(!empty($tags)){
			$config['keywords'] = $tags;
		}else{
			$config['keywords'] = $news['title'].'-'.$config['keywords'];
		}
		if(empty($news['video']) || empty($news['pic'])) $config['description'] = msubstr(strip_tags(htmlspecialchars($news['content'])),0,120,'utf-8',false);
		else $config['description'] = $news['title'].'-'.$config['description'];
		$this->assign('config',$config);
		$this->tagList();
		$this->display();
	}
	
	
	/*审贴*/
	public function ticket(){
		//网站配置
		$config = M('Config')->find();
		if($_GET['p']){
			$config['title'] = '审贴-第'.(int)$_GET['p'].'页-'.$config['stitle'];
		}else{
			$config['title'] = '审贴-'.$config['stitle'];
		}
		$this->assign('config',$config);
		$this->assign('ticketmsg',C('ticketmsg'));
		
		$this->display();
	}
	
	/*Ajax检测用户发布内容*/
	public function checkForm(){
		if(md5($_POST['verify']) != $_SESSION['verify']) exit('-1');
		$content = trim($_POST['content']);
		$video = trim($_POST['video']);
		if(empty($content) && empty($_POST['pic']) && empty($video)) exit('-3');
		if(count(explode(' ',trim($_POST['tag'])))>3) exit('-4');
		if(!empty($_POST['pic']) && !empty($video)) exit('-5');
		if(!empty($video) && !in_array(array_pop(explode('.',$video)),array('swf','flv')) && !get_headers($video)) exit('-6');
		if(!empty($_POST['email']) && !preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/i",$_POST['email'])) exit('-7');
	}
	
	public function checkAdd(){
		$str="/YiCms/Tpl/Home/".C('DEFAULT_THEME')."/Public/";
		$this->assign('style',$str);
		//dump($_POST);
		if($_COOKIE['add_time']+C('add_time') > time()){
			$this->error('不能频繁灌水');
		}
		setcookie("add_time",time());
		//获取用户UID
		if(empty($_SESSION['uid']) || $_POST['anonymous']==true){
			$_POST['uid'] = '1';
			$_POST['author'] = '匿名发布';
		}else{
			$_POST['uid'] = $_SESSION['uid'];
			$_POST['author'] = $_SESSION['uname'];
		}
		if(C('opencws')){
			/*导入中文分词类，分词后加上链接*/    
			import("@.ORG.initcws");
			$cws = new initcws();
			$taglist = M('Tag')->field('name,url')->order('taxis ASC,id DESC')->limit(20)->select();		
			$_POST['content'] = str_replace('#','',zen_key_replace($cws->cws($_POST['content']),$taglist));
		}else{
			$_POST['content'] =  trim($_POST['content']);
			$_POST['content'] = strip_tags($_POST['content']);
		}
		//时间
		$_POST['time'] = $_SERVER['REQUEST_TIME'];
		$_POST['tag'] =  strip_tags(trim($_POST['tag']));
		if(!empty($_SESSION['uid'])){
			$uid = $_SESSION['uid'];
			$user = M('User')->field('email')->where("uid = $uid")->find();
			$_POST['email'] = $user['email'];
		}
		if($_FILES['pic']['error'] != '4'){
			import("@.ORG.UploadFile");
			$upload = new UploadFile();
			/*限制上传文件的大小  单位是B 1024B=1K 1024K=1M 1024M=1G 下面约是20M*/  
			$upload->maxSize =20971520;
			$upload->allowExts = explode(',','jpg,gif,png,jpeg');
			$upload->savePath ='Public/news/';
			if($_FILES['pic']['type']!='image/gif'){
				$upload->thumb=true;
				$upload->imageClassPath = '@.ORG.Image';
				$upload->thumbPrefix = 'm_,s_';
				$upload->thumbMaxWidth  = C('newsmwidth').','.C('newsswidth');
				$upload->thumbMaxHeight = C('newsmheight').','.C('newsmheight');
				$upload->thumbRemoveOrigin = true;
			}
			$upload->saveRule = uniqid;
			if(!$upload->upload()){			$this->error($upload->getErrorMsg());
			}else{
				$uploadList = $upload->getUploadFileInfo();
				$_POST['pic'] = $uploadList[0]['savename'];
				if($_FILES['pic']['type']!='image/gif'){
					import("@.ORG.Image");
					Image::watermark($uploadList[0]['savepath'].'m_'.$uploadList[0]['savename']);
					Image::watermark($uploadList[0]['savepath'].'s_'.$uploadList[0]['savename']);
				}else{
					copy($uploadList[0]['savepath'].$uploadList[0]['savename'],$uploadList[0]['savepath'].'m_'.$uploadList[0]['savename']);
					copy($uploadList[0]['savepath'].$uploadList[0]['savename'],$uploadList[0]['savepath'].'s_'.$uploadList[0]['savename']);
					unlink($uploadList[0]['savepath'].$uploadList[0]['savename']);
				}	
			}
			$_POST['pid'] = 3;
		}elseif(!empty($_POST['video'])){
			$_POST['video'] =  htmlspecialchars(trim($_POST['video']));
			$_POST['pid'] = 4;
		}else{
			$_POST['pid'] = 2;
		}
		if(empty($_POST['title'])){

				$_POST['title'] = msubstr(strip_tags($_POST['content']),0,20,'utf-8',false);

		}else{
			$_POST['title']  = htmlspecialchars(strip_tags($_POST['title']));
		}
		if(substr_count($_POST['title'],'<')){
			$_POST['title'] = '';
		}
	
		$vo = M('News')->add($_POST);
		if(!$vo) $this->error('发布失败!您可以重新试试.');
		if(empty($_SESSION['uid']) || !empty($_POST['anonymous'])) $uid='1';
		else $uid = $_SESSION['uid'];
		M('User')->where("uid = $uid")->setInc('articles');
		M('User')->where("uid = $uid")->setInc('score',C('add_score'));
		$this->assign('vo',$vo);
		$this->about();
		//网站配置
		$config = M('Config')->find();
		$config['title'] = '发贴成功-'.$config['stitle'];
		$this->assign('config',$config);
		$this->tagList();
		if(!empty($_SESSION['tweibo'])){
			require_once './tweibo/Config.php';
			require_once './tweibo/Tencent.php';
			OAuth::init($client_id, $client_secret);
			Tencent::$debug = $debug;
			if ($_SESSION['t_access_token'] || ($_SESSION['t_openid'] && $_SESSION['t_openkey'])) {//用户已授权
				if(!empty($_POST['pic'])){
					$params = array(
						'content' => msubstr($_POST['content'],0,120).C('URL'),
						'pic_url' => C('YICMS_PUBLIC').'/news/m_'.$_POST['pic']
					);
					$r = Tencent::api('t/add_pic_url', $params, 'POST');
				}else{
					$params = array(
						'content' => msubstr($_POST['content'],0,120).C('URL'),
					);
					$r = Tencent::api('t/add', $params, 'POST');
				}
			}
		}
	
		$this->display();
	}

	/*获取标签列表*/
	public function tagList(){
	
		$tagList = M('Tag')->field('distinct(name),url')->order('taxis ASC,id DESC')->limit(C('tagnum'))->select();
		foreach($tagList as $key=>$value){
			if(empty($value['url'])){
				$tagList[$key]['url'] = '<a href="/tag/'.$value['name'].'">'.$value['name'].'</a>';
			}else{
				$tagList[$key]['url'] = '<a href="'.$value['url'].'" target="_blank">'.$value['name'].'</a>';
			}
			
		}
		
		$this->assign('tagList',$tagList);
	}
	
	
}